package com.assistant.codegen.modules.model.domain.column;

import com.assistant.codegen.modules.model.domain.DataSource;
import com.assistant.codegen.modules.model.domain.column.sub.*;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

import static java.sql.Types.*;

public class ColumnFactory {

    public static ModelColumn create(String type) {
        switch (type) {
            case "string":
                return new StringColumn();
            case "boolean":
                return new BooleanColumn();
            case "integer":
                return new IntegerColumn();
            default:
                throw new IllegalArgumentException("暂时不支持" + type + "类型的字段");
        }
    }

    public static List<ModelColumn> create(DataSource dataSource, String database, String tableName) throws SQLException {
        DriverManager.registerDriver(new com.mysql.cj.jdbc.Driver());
        final Connection connection = DriverManager.getConnection(dataSource.getUrl(), dataSource.getUsername(), dataSource.getPassword());
        final DatabaseMetaData metaData = connection.getMetaData();
        final ResultSet resultSet = metaData.getTables(database, null, tableName, new String[]{"TABLE"});

        List<ModelColumn> result = new ArrayList<>();
        while (resultSet.next()) {
            final ResultSet columns = metaData.getColumns(database, null, tableName, "");
            while (columns.next()) {
                final ModelColumn modelColumn = create(columns);
                result.add(modelColumn);
            }
        }
        return result;
    }

    public static ModelColumn create(ResultSet resultSet) throws SQLException {
        switch (resultSet.getInt("DATA_TYPE")) {
            case BIT:
                return new BooleanColumn(resultSet);
            case TINYINT:
                if (resultSet.getInt("COLUMN_SIZE") == 1) {
                    return new BooleanColumn(resultSet);
                }
            case SMALLINT:
            case INTEGER:
            case BIGINT:
                return new IntegerColumn(resultSet);
            case CHAR:
            case VARCHAR:
            case LONGVARCHAR:
                return new StringColumn(resultSet);
            case DATE:
                return new DateColumn(resultSet);
            case TIME:
                return new TimeColumn(resultSet);
            case TIMESTAMP:
                return new DateTimeColumn(resultSet);
            case DECIMAL:
                return new DecimalColumn(resultSet);
            case FLOAT:
            case DOUBLE:
            case NUMERIC:
            case REAL:
            case BINARY:
            case VARBINARY:
            case LONGVARBINARY:
            case BLOB:
            case CLOB:
            default:
                throw new IllegalArgumentException(resultSet.getString("TYPE_NAME") + "类型暂时不支持");
        }
    }
}
